package com.house.rent.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.base.lib.mvp.present.BasePresenter;
import com.base.lib.ui.dialog.SelectMenuDialog;
import com.house.rent.App;
import com.house.rent.R;
import com.house.rent.entity.HouseEntity;
import com.house.rent.entity.UserEntity;
import com.house.rent.util.BASE64Utils;
import com.house.rent.util.ViewUtils;
import com.house.rent.view.XImageView;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class EditHouseActivity extends BaseActivity {
    private static final int CAMERA_REQUEST = 0x111;
    private static final int PICK_REQUEST = 0x222;

    @BindView(R.id.edt_public_communityName)
    EditText mEdtCommunityName;

    @BindView(R.id.edt_public_floor)
    EditText mEdtFloor;

    @BindView(R.id.edt_public_apartment)
    EditText mEdtApartment;

    @BindView(R.id.edt_public_area)
    EditText mEdtArea;


    @BindView(R.id.edt_public_address)
    EditText mEdtAddress;

    @BindView(R.id.edt_public_price)
    EditText mEdtPrice;

    @BindView(R.id.edt_public_desc)
    EditText mEdtDesc;

    /**
     * 房源照片
     */
    @BindView(R.id.iv_house_img1)
    XImageView mIvImage1;
    @BindView(R.id.iv_house_img2)
    XImageView mIvImage2;
    @BindView(R.id.iv_house_img3)
    XImageView mIvImage3;

    private long mHouseId;
    private HouseEntity mHouseEntity;
    private Uri imageUri;
    private List<String> bitmapList = new ArrayList<>();

    public static void start(Context context, long houseId) {
        Intent starter = new Intent(context, EditHouseActivity.class);
        starter.putExtra("houseId", houseId);
        context.startActivity(starter);
    }

    @Override
    public void initIntent(Intent intent) {
        super.initIntent(intent);
        mHouseId = getIntent().getLongExtra("houseId", 0);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_edit_house;
    }

    @Override
    protected void initTop() {
        setTitle("编辑信息");
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @Override
    protected void initListeners() {

    }

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected void initData() {
        addParams("id", mHouseId);
        sendRequest("house-info/info", HouseEntity.class);
    }

    private void initHouseView() {
        //填充界面数据
        mEdtCommunityName.setText(mHouseEntity.getCommunityName());

        mEdtFloor.setText(mHouseEntity.getFloor() + "");
        mEdtApartment.setText(mHouseEntity.getApartment());
        mEdtArea.setText(mHouseEntity.getSize() + "");
        mEdtAddress.setText(mHouseEntity.getAddress());
        mEdtPrice.setText(mHouseEntity.getCeilingPrice() + "");
        mEdtDesc.setText(mHouseEntity.getDescription());
        String[] photos = mHouseEntity.getHousePhoto().split(",");
        for (int i = 0; i < photos.length; i++) {
            String url = photos[i];
            switch (i) {
                case 0:
                    mIvImage1.setImageUrl(url);
                    break;
                case 1:
                    mIvImage2.setImageUrl(url);
                    break;
                case 2:
                    mIvImage3.setImageUrl(url);
                    break;
                default:
                    break;
            }
            bitmapList.add(url);
        }
    }


    @OnClick({R.id.btn_public, R.id.btn_add_pic})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_add_pic:
                if (bitmapList.size() >= 3) {
                    showMessage("只能添加3张图片");
                    return;
                }
                showSelectPicDialog();
                break;
            case R.id.btn_public:
                createHouse();
                break;
            default:
                break;
        }
    }


    private void createHouse() {
        String communityName = mEdtCommunityName.getText().toString().trim();
        String floor = mEdtFloor.getText().toString().trim();
        String apartment = mEdtApartment.getText().toString().trim();
        String area = mEdtArea.getText().toString().trim();
        String address = mEdtAddress.getText().toString().trim();
        String price = mEdtPrice.getText().toString().trim();
        String desc = mEdtDesc.getText().toString().trim();

        if (TextUtils.isEmpty(communityName)) {
            showMessage("请输入小区名称");
            return;
        }

        if (TextUtils.isEmpty(floor)) {
            showMessage("请输入房源楼层");
            return;
        }
        if (TextUtils.isEmpty(apartment)) {
            showMessage("请输入房源户型");
            return;
        }
        if (TextUtils.isEmpty(area)) {
            showMessage("请输入房源面积");
            return;
        }
        if (TextUtils.isEmpty(address)) {
            showMessage("请输入房源地址");
            return;
        }
        if (TextUtils.isEmpty(price)) {
            showMessage("请输入房源价格");
            return;
        }
        if (TextUtils.isEmpty(desc)) {
            showMessage("请输入房源描述");
            return;
        }

        //    name	是	string	名称
//    size	否	int	面积
//    type	是	int	类型 0-出售 1-求购 2-求租 3-出租
//    description	否	string	描述
//    housePhoto	否	string	房间照片
//    ceilingPrice	是	int	最高价格
//    minimumPrice	是	int	最低价格


        showLoading("正在更新...");

        UserEntity userEntity = App.getInstance().getUserEntity();

        addParams("id", mHouseEntity.getId());
        addParams("userId", userEntity.getId());
        addParams("nickName", userEntity.getNickName());
        addParams("type", mHouseEntity.getType());
        addParams("communityName", communityName);
        addParams("floor", floor);
        addParams("apartment", apartment);
        addParams("size", area);
        addParams("address", address);
        addParams("ceilingPrice", price);
        addParams("description", desc);

        StringBuilder builder = new StringBuilder();
        for (String bitmapStr : bitmapList) {
            builder.append(bitmapStr).append(",");
        }
        addParams("housePhoto", builder.toString());


        sendRequest("house-info/update", null);
    }

    @Override
    protected void onRequestSuccess(String reqId, Object obj) {
        super.onRequestSuccess(reqId, obj);
        switch (reqId) {
            case "house-info/info":
                if (obj instanceof HouseEntity) {
                    mHouseEntity = (HouseEntity) obj;
                    initHouseView();
                }
                break;
            case "house-info/update":
                showMessage("更新成功");
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Bitmap bitmap = null;
            switch (requestCode) {
                case CAMERA_REQUEST:
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_REQUEST:
                    imageUri = data.getData();
                    String imagePath = ViewUtils.getAbsolutePath(this, imageUri);
                    bitmap = BitmapFactory.decodeFile(imagePath);
                    break;
                default:
                    break;
            }
            if (bitmap != null) {
                String bitmapStr = BASE64Utils.bitmap2String(bitmap);
                bitmapList.add(bitmapStr);
                switch (bitmapList.size()) {
                    case 1:
                        mIvImage1.setImageBitmap(bitmap);
                        break;
                    case 2:
                        mIvImage2.setImageBitmap(bitmap);
                        break;
                    case 3:
                        mIvImage3.setImageBitmap(bitmap);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void showSelectPicDialog() {
        SelectMenuDialog menuDialog = new SelectMenuDialog(mContext);
        menuDialog.setMenu(new String[]{"选择相册", "相机"}, (dialog, item, position) -> {
            dialog.dismiss();
            switch (position) {
                case 0:
                    ViewUtils.openGallery(this, PICK_REQUEST);
                    break;
                default:
                    imageUri = ViewUtils.openCamera(this, CAMERA_REQUEST);
                    break;
            }
        });
        menuDialog.show();
    }
}
